package com.yuliang.job;

import com.yuliang.domain.entity.Article;
import com.yuliang.service.ArticleService;
import com.yuliang.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Component
public class UpdateViewJob {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ArticleService articleService;

    @Scheduled(cron = "0 0/1 * * * ?") //每一分钟执行一次
    public void updateViewJob(){
        //从redis中获取浏览量
        Map<String, Integer> map = redisCache.getCacheMap("article:viewCount");
        //更新数据库的浏览量
        Set<Map.Entry<String, Integer>> entries = map.entrySet();

        Set<Article> set = new HashSet<>();
        for (Map.Entry<String,Integer> entry: entries) {
            Article article = new Article();
            article.setId(Long.valueOf(entry.getKey()));
            article.setViewCount(Long.valueOf(entry.getValue()));
            set.add(article);
        }
        articleService.updateBatchById(set);
    }
}
